#!/usr/bin/env node
const commander = require('commander');
const inquirer = require('inquirer');
const fs = require('fs');
const path = require('path');
const { dirname } = require('path');
const dataJson = require('./data.json')
commander.command('changeName [old] [new]').action((oldName,newName)=>{
    // 判断oldName是否存在 1、绝对匹配 2、模糊匹配
    // 获取当前目录
    const files = fs.readdirSync(__dirname)
    // 判断是否绝对匹配
    const haveOldFile = files.find(item=>item===oldName)
    if(haveOldFile){
        fs.renameSync(oldName,newName)
    } else {
        // 进行模糊匹配
        const filterList = files.filter(item=>item.includes(oldName))
        let ind= 0; //默认下标
        filterList.forEach(item=>{
            ind+=1
            fs.renameSync(item,`${newName.split('.')[0]}(${ind}).${newName.split('.')[1]}`)
        })
    }
})
// 删除文件或文件夹
commander.command('deleteFile [fileName]').action(name=>{
    // 1. 判断name是否存在
    // 2. 判断是文件还是文件夹
    // 3. 文件直接删除  文件夹遍历所有子文件并删除
    const isHave = fs.existsSync(name);
    if(isHave) {
        delFile(__dirname, name)
    } else {
        console.log('没有这个文件')
    }
})
function delFile(dirName, name) {
    const url = path.join(dirName,name)
    const stat = fs.statSync(url)
    if(stat.isFile()) {
        fs.unlinkSync(url)  
    } else {
        const files = fs.readdirSync(url)
        files.forEach(item => {
            delFile(url,item)
        })
        fs.rmdirSync(url)
    }
}

commander.command('create [projectName]').action(name=>{
    // 1. 是否重复
    const isHave = fs.existsSync(name)
    if(isHave) {
        console.log('文件已经存在')
    } else{
        // 2. 选择 vue 或 react
        inquirer.prompt([
            {
                type:'list',
                message:"选择项目类型",
                choices: ['vue','react'],
                name: "type"
            }
        ]).then(res=>{
            console.log(res)
            // 3. 生成一个文件夹
            fs.mkdirSync(name)
            initProjectName(dataJson, name)
        })
    }
})
function initProjectName(obj, url) {
    console.log(obj,url)
    // 是文件还是文件夹
    if(obj.dirname) {
        // 文件夹
        fs.mkdirSync(path.join(url,obj.dirname))
        obj.children?obj.children.forEach(item=>{
            initProjectName(item, path.join(url, obj.dirname))
        }):null
    } else {
        // 文件
        fs.writeFileSync(String(path.join(url,obj.filename)),'')
    }
}
commander.parse(process.argv)